//
//  StoreViewController.swift
//  Reader
//
//  Created by home on 2019/10/10.
//  Copyright © 2019 codeguesser. All rights reserved.
//

import UIKit
import SwiftyJSON
class StoreViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
    
    @IBOutlet weak var tableView:UITableView!
    var dataList:[JSON] = []{
        didSet{
            self.tableView.reloadData()
        }
    }
    //MARK: - system methods
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        self.navigationItem.rightBarButtonItems = [UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addBook)),UIBarButtonItem(barButtonSystemItem: .bookmarks, target: self, action: #selector(gotoLocal))]
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .organize, target: self, action: #selector(gotoSetting))
        self.navigationItem.largeTitleDisplayMode = .automatic
        self.navigationItem.title = "网上书店"
        self.navigationController?.navigationBar.prefersLargeTitles = true
        
        tableView.refreshControl = UIRefreshControl()
        tableView.refreshControl?.addTarget(self, action:
                                           #selector(handleRefreshControl),
                                           for: .valueChanged)
        self.handleRefreshControl()
        DispatchQueue.main.after(0.3) { [weak self] in
            if let SSelf = self,let read = ReadModel.lastRead(),let book = BookModel.model(["\(read.bid)"]),let chapter = ChapterModel.model(["\(read.bid)","\(read.cid)"]){
                let vc = ChapterViewController(nibName: ChapterViewController.identifier)
                vc.data = book.json
                SSelf.navigationController?.pushViewController(vc, animated: false)
                
                let vc1 = DetailViewController(nibName: DetailViewController.identifier)
                vc1.data = chapter.json
                vc1.modalPresentationStyle = .fullScreen
                SSelf.navigationController?.present(vc1, animated: true, completion: {
                    vc1.resizeTexts()
                })
            }
        }
        
    }
    //MARK: - tableview methods
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .value1, reuseIdentifier: UITableViewCell.identifier)
        cell.textLabel?.text = dataList[indexPath.row]["name"].stringValue
        cell.detailTextLabel?.text = dataList[indexPath.row]["id"].stringValue
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        let vc = ChapterViewController(nibName: ChapterViewController.identifier)
        vc.data = dataList[indexPath.row]
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    //MARK: - custom methods
    @objc func handleRefreshControl() {
       // Update your content…
        RD.request("http://wangshuguan.pythonanywhere.com/app/").responseZWTJSON { (response,_,_)  in
            if let v = response.value{
                self.dataList.removeAll(keepingCapacity: false)
                self.dataList.append(contentsOf: JSON(v)["result"].arrayValue)
                
            }
            self.tableView.refreshControl?.endRefreshing()
        }
    }
    @objc func gotoSetting(){
        let vc = SettingViewController(nibName: SettingViewController.identifier)
        self.navigationController?.pushViewController(vc, animated: true)
    }
    @objc func addBook(){
        
        let vc = StoreAddViewController(nibName: StoreAddViewController.identifier)
        let localMax:Int64 = BookModel.findAll(limit:1,sort: [("id",false)])?.first?.id ?? 0
        let serverMax:Int = self.dataList.map({$0["id"].intValue}).max() ?? 0
        vc.index = max(Int(localMax),serverMax) + 1
        vc.addAction = {[weak self] (id,name,link) in
            if let SSelf = self{
                SSelf.dataList.append(JSON(["url" : link,"name" : name,"id" : id]))
            }
        }
        self.navigationController?.pushViewController(vc, animated: true)
    }
    @objc func gotoLocal(){
        let vc = LocalBooksViewController(nibName: LocalBooksViewController.identifier)
        self.navigationController?.pushViewController(vc, animated: true)
    }
}

